//
//  KeyworkMatchManager.m
//  ASR_Demo
//
//  Created by marco on 16/3/10.
//  Copyright © 2016年 Marco. All rights reserved.
//

#import "KeyworkMatchManager.h"


@interface KeyworkMatchManager ()

@property (nonatomic,copy) NSString *keywordZH;
@property (nonatomic,copy) NSString *keywordUY;

@end

@implementation KeyworkMatchManager




+ (instancetype)sharedManager
{
    static KeyworkMatchManager* manager = nil;
//    dispatch_once_t token;
//    dispatch_once(&token, ^{
//        manager = [self new];
//    });
    if( !manager )
    {
        manager = [self new];
    }
    return manager;
}

- (instancetype) init
{
    if( self = [super init] )
    {
        [self readData];
    }
    return self;
}

-(void) readData
{
    NSString *uyPath = [[NSBundle mainBundle] pathForResource:FILENAME_UY ofType:nil];
    NSString *zhPath = [[NSBundle mainBundle] pathForResource:FILENAME_ZH ofType:nil];
    _keywordZH = [NSString stringWithContentsOfFile:zhPath encoding:NSUTF8StringEncoding error:nil];
    _keywordUY = [NSString stringWithContentsOfFile:uyPath encoding:NSUTF8StringEncoding error:nil];
}


#pragma mark 匹配是否有关键字
- (BOOL) matchKeywordForZH:(NSString*)pWord
{
    return [self matchKeyword:pWord keywordsLibrary:_keywordZH];
}
- (BOOL) matchKeywordForUY:(NSString*)pWord
{
    return [self matchKeyword:pWord keywordsLibrary:_keywordUY];
}

- (BOOL) matchKeyword:(NSString*)pWord keywordsLibrary:(NSString*)pLibrary
{
    NSArray *list=[pLibrary componentsSeparatedByString:@"\n"];
    
    BOOL bRet = NO;
    
    for (NSString* word in list) {
        
        if([pWord rangeOfString:word].location != NSNotFound)
        {
            bRet = YES;
            break;
        }
    }
    
    return bRet;

}

#define 检测关键字的位置

- (NSRange) matchKeywordRangeForZH:(NSString*)pWord
{
    return [self matchKeywordRange:pWord keywordsLibrary:_keywordZH];
}
- (NSRange) matchKeywordRangeForUY:(NSString *)pWord
{
    return [self matchKeywordRange:pWord keywordsLibrary:_keywordUY];
}

- (NSRange) matchKeywordRange:(NSString*)pWord keywordsLibrary:(NSString*)pLibrary
{
    NSRange range = NSMakeRange(NSNotFound, 0);
    
    NSArray *list=[pLibrary componentsSeparatedByString:@"\n"];
    for (NSString* word in list) {
        
       range = [pWord rangeOfString:word];
        if(range.location != NSNotFound)
        {
            break;
        }
    }
    return range;
}

@end
